package ahblue.cn.tanzi.ui.circle;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import ahblue.cn.tanzi.R;
import ahblue.cn.tanzi.data.source.ApiCallback;
import ahblue.cn.tanzi.data.source.RemoteRepository;
import ahblue.cn.tanzi.model.circle.DynamicComment;
import ahblue.cn.tanzi.util.GlideApp;
import ahblue.cn.tanzi.util.TimeUtils;
import ahblue.cn.tanzi.view.MyLinearLayoutManager;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用于显示动态评论
 */
public class DynamicCommentFragment extends Fragment {

    private static final String ARG_DYNAMIC_ID = "ARG_DYNAMIC_ID";

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    private DynamicCommentAdapter mCommentAdapter;
    private MyLinearLayoutManager myLinearLayoutManager;
    private List<DynamicComment> mCommentList = new ArrayList<>();

    private int mDynamicId;
    private int mPage = 0;
    private final static int PAGE_COUNT = 10;

    private boolean mIsCommentRefresh;
    private boolean mIsCommentLoadMore;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param dynamicId 动态ID.
     * @return A new instance of fragment ArticleListFragment.
     */
    public static DynamicCommentFragment newInstance(int dynamicId) {
        DynamicCommentFragment fragment = new DynamicCommentFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_DYNAMIC_ID, dynamicId);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getArguments() != null) {
            mDynamicId = getArguments().getInt(ARG_DYNAMIC_ID);
        }


    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_recycler_only, container, false);
        ButterKnife.bind(this, view);

        initView();

        mRecyclerView.setFocusableInTouchMode(false);
        mRecyclerView.requestFocus();
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        initData();
    }

    public void initData() {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotDynamicCommentList(mPage, PAGE_COUNT, mDynamicId, mDynamicCommentCallback);
    }

    private void initView() {
        mCommentAdapter = new DynamicCommentAdapter(mCommentList);
        mRecyclerView.setAdapter(mCommentAdapter);
        myLinearLayoutManager = new MyLinearLayoutManager(getContext());
        myLinearLayoutManager.setScrollEnabled(false);
        mRecyclerView.setLayoutManager(myLinearLayoutManager);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPage = 0;
                mCommentList.clear();
                mIsCommentRefresh = true;

                loadCommentPage(mPage);
            }
        });
        mRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPage += 1;
                mIsCommentLoadMore = true;

                loadCommentPage(mPage);
            }
        });

    }

    public void setCanScrollable(boolean canScrollable){
        myLinearLayoutManager.setScrollEnabled(canScrollable);
    }

    private void loadCommentPage(int page) {
        RemoteRepository repo = RemoteRepository.getsInstance();
        repo.getBigShotDynamicCommentList(page, PAGE_COUNT, mDynamicId, mDynamicCommentCallback);
    }

    /**
     * 获取动态评论的回调函数。
     */
    ApiCallback<List<DynamicComment>> mDynamicCommentCallback = new ApiCallback<List<DynamicComment>>() {

        @Override
        public void onSuccess(List<DynamicComment> data) {
            if (data == null) {
                return;
            }
            mCommentList.addAll(data);
            mCommentAdapter.notifyDataSetChanged();
            if (getActivity() != null && !getActivity().isFinishing()) {
                ((DynamicDetailActivity)getActivity()).setCommentCount(mCommentList.size());
            }

          if (mIsCommentRefresh) {
                mIsCommentRefresh = false;
                mRefreshLayout.finishRefresh(true);
            }

            if (mIsCommentLoadMore) {
                mIsCommentLoadMore = false;
                mRefreshLayout.finishLoadmore(true);
            }

            if (chanageHeightListener != null){
                chanageHeightListener.onDataResult(190 * data.size());
            }
        }

        @Override
        public void onFailed(String errorMsg) {
            if (mIsCommentRefresh) {
                mIsCommentRefresh = false;
                mRefreshLayout.finishRefresh(false);
            }

            if (mIsCommentLoadMore) {
                mIsCommentLoadMore = false;
                mRefreshLayout.finishLoadmore(false);
            }
        }
    };

    /**
     * 文章列表的adapter
     */
    class DynamicCommentAdapter extends BaseQuickAdapter<DynamicComment, BaseViewHolder> {

        DynamicCommentAdapter(@Nullable List<DynamicComment> data) {
            super(R.layout.item_dynamicdetails_comment, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, DynamicComment item) {
            ImageView iv = helper.getView(R.id.iv_comment_head);
            GlideApp.with(iv)
                    .load(item.member_avatar)
                    .placeholder(R.drawable.person_icon_head)
                    .error(R.drawable.person_icon_head)
                    .into(iv);

            helper.setText(R.id.commentTv, item.member_name);
            helper.setText(R.id.tv_comment_content, item.comment_content);
            helper.setText(R.id.tv_comment_time, TimeUtils.getStandardDate(item.add_time));
        }
    }

    public interface ChanageHeightListener{
        void onDataResult(int height);
    }

    private ChanageHeightListener chanageHeightListener;

    public void setChanageHeightListener(ChanageHeightListener chanageHeightListener){
        this.chanageHeightListener = chanageHeightListener;
    }
}
